package com.ktjy.controller;

import com.ktjy.entity.vo.SysUserVo;
import com.ktjy.service.ISysRoleRightService;
import com.ktjy.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author lqm
 * @ClassName LoginController
 * @description: TODO
 */
@Controller
public class LoginController {

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    ISysRoleRightService sysRoleRightService;



    @RequestMapping("/")
    public String login() {
        return "login";
    }



    @RequestMapping("/logout")
    public String logout() {
        Subject currentUser=SecurityUtils.getSubject();
        currentUser.logout();
        return "redirect:/";
    }

    @RequestMapping("/doLogin")
    public String doLogin(String usrName, String usrPassword, Model model, HttpSession session) {

//        SysUserVo sysUser=sysUserService.getUserByUsrNameAndPwd(usrName,usrPassword);
        try {
            //创建账号密码令牌
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);

            //三大组件  Subject   SecurityManager  realm
            //获取当前用户
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.login(token);

            //从shiro主体中获取认证的用户
            SysUserVo sysUser = (SysUserVo) currentUser.getPrincipal();
//            sysUser.getRole().setRights(sysRoleRightService.getRightByUserRoleId(sysUser.getUsrRoleId()));

            session.setAttribute("loginUser", sysUser);
            return "main";
        }catch (UnknownAccountException e){
            model.addAttribute("message","账号密码错误！");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("message","账号已锁定！");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("message","账号密码错误！");
            return "login";
        }

    }


    @RequestMapping("/mian")
    public String main() {
        return "mian";
    }


    @RequestMapping("/403")
    public String unAuth() {
        return "403";
    }
}
